import { defineStore } from 'pinia'
import { homeworkApi } from '@/api/homework'

export const useHomeworkStore = defineStore('homework', {
  state: () => ({
    currentHomework: null,
    currentHomeworks: [],
    homeworkDetails: [],
    loading: false
  }),

  actions: {
    async fetchCurrentHomework(studentId) {
      try {
        this.loading = true

        // 获取所有当前作业
        const response = await homeworkApi.getAllCurrent(studentId)
        this.currentHomeworks = response.data

        // 获取第一个作业作为当前作业（保持兼容性）
        if (this.currentHomeworks.length > 0) {
          this.currentHomework = this.currentHomeworks[0]

          // 获取所有作业的明细
          this.homeworkDetails = []
          for (const homework of this.currentHomeworks) {
            await this.fetchHomeworkDetails(homework.id)
          }
        } else {
          this.currentHomework = null
          this.homeworkDetails = []
        }

        return response
      } catch (error) {
        this.currentHomework = null
        this.currentHomeworks = []
        this.homeworkDetails = []
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchHomeworkDetails(homeworkId) {
      try {
        const response = await homeworkApi.getDetails(homeworkId)
        // 为每个详情添加homeworkId用于前端显示
        const detailsWithHomeworkId = response.data.map(detail => ({
          ...detail,
          homeworkId: homeworkId
        }))
        // 合并到现有详情列表
        this.homeworkDetails = [...this.homeworkDetails, ...detailsWithHomeworkId]
        return response
      } catch (error) {
        console.error(`获取作业${homeworkId}明细失败:`, error)
        throw error
      }
    },

    async startHomework(homeworkId) {
      try {
        const response = await homeworkApi.start(homeworkId)
        if (this.currentHomework) {
          this.currentHomework.status = 1
          this.currentHomework.actualStartTime = new Date().toISOString()
        }
        return response
      } catch (error) {
        throw error
      }
    },

    async completeHomeworkDetail(detailId) {
      try {
        const response = await homeworkApi.completeDetail(detailId)
        // 更新本地状态
        const detail = this.homeworkDetails.find(d => d.id === detailId)
        if (detail) {
          detail.isCompleted = true
          detail.completedTime = new Date().toISOString()
        }

        if (this.currentHomework) {
          this.currentHomework.completedItems++
          if (this.currentHomework.completedItems === this.currentHomework.totalItems) {
            this.currentHomework.status = 2
            this.currentHomework.actualEndTime = new Date().toISOString()
          }
        }

        return response
      } catch (error) {
        throw error
      }
    },

    async createHomework(data) {
      try {
        const response = await homeworkApi.create(data)
        return response
      } catch (error) {
        throw error
      }
    },

    async updateHomework(id, data) {
      try {
        const response = await homeworkApi.update(id, data)
        return response
      } catch (error) {
        throw error
      }
    },

    async deleteHomework(id) {
      try {
        const response = await homeworkApi.delete(id)
        return response
      } catch (error) {
        throw error
      }
    },

    // 动态添加作业项
    async addHomeworkDetail(homeworkId, detailData) {
      try {
        const response = await homeworkApi.addDetail(homeworkId, detailData)

        // 刷新作业详情
        await this.fetchHomeworkDetails(homeworkId)

        // 更新作业总项目数
        if (this.currentHomework && this.currentHomework.id === homeworkId) {
          this.currentHomework.totalItems++
        }

        return response
      } catch (error) {
        throw error
      }
    },

    // 删除未完成作业项
    async deleteHomeworkDetail(homeworkId, detailId) {
      try {
        const response = await homeworkApi.deleteDetail(homeworkId, detailId)

        // 从本地状态中移除该明细
        this.homeworkDetails = this.homeworkDetails.filter(d => d.id !== detailId)

        // 更新作业总项目数和必须完成项目数
        if (this.currentHomework && this.currentHomework.id === homeworkId) {
          const deletedDetail = this.homeworkDetails.find(d => d.id === detailId)
          if (deletedDetail) {
            this.currentHomework.totalItems--
            if (deletedDetail.isRequired) {
              this.currentHomework.requiredCompletedItems--
            }
          }
        }

        return response
      } catch (error) {
        throw error
      }
    },

    // 修改作业项内容
    async updateHomeworkDetail(homeworkId, detailId, detailData) {
      try {
        const response = await homeworkApi.updateDetail(homeworkId, detailId, detailData)

        // 更新本地状态
        const detail = this.homeworkDetails.find(d => d.id === detailId)
        if (detail) {
          detail.content = detailData.content
          if (detailData.isRequired !== undefined) {
            detail.isRequired = detailData.isRequired
          }
        }

        return response
      } catch (error) {
        throw error
      }
    },

    // 调整作业项必须/非必须属性
    async updateHomeworkDetailRequired(homeworkId, detailId, isRequired) {
      try {
        const response = await homeworkApi.updateDetailRequired(homeworkId, detailId, isRequired)

        // 更新本地状态
        const detail = this.homeworkDetails.find(d => d.id === detailId)
        if (detail) {
          detail.isRequired = isRequired
        }

        return response
      } catch (error) {
        throw error
      }
    }
  }
})